package com.yisin.www.chat;

import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.yisin.pbox.frame.log.ILogger;
import com.yisin.pbox.frame.log.LogFactory;
import com.yisin.pbox.frame.util.DateUtil;
import com.yisin.pbox.frame.util.HttpUtil;
import com.yisin.pbox.frame.util.StringUtil;

public class RobotReThread implements Runnable {
	private static ILogger logger = LogFactory.getDefaultLogger(RobotReThread.class);
	
	private static String url = "http://www.tuling123.com/openapi/api";
	private static String[] param = {
		"key=439c0e518a953140d9b6e4ba4d0a998c&info="
	};
	
	String[] histroy = {"", ""};
	
	private String touser = "";
	private String fromuser = "";
	private String msg = "";
	private int timeout = 500;
	private Socket tosoc = null;

	public RobotReThread(Socket tosoc, String touser, String fromuser, String msg, int timeout) {
		this.fromuser = fromuser;
		this.touser = touser;
		this.msg = msg;
		this.tosoc = tosoc;
		this.timeout = timeout;
	}

	public void run() {
		String temp = "", temp2 = "";
		try {
			logger.info("fromuser=" + fromuser + "，touser=" + touser);
			
			if(fromuser == null){
				fromuser = getRobot(touser);
				if(fromuser.equals(touser)){
					return;
				}
			}
			msg = msg.replaceAll("&nbsp;", " ").trim();
			// 收藏
			if(msg.length() > 2 && msg.length() < 10){
				if(msg.substring(0, 1).equals("@") && msg.indexOf(" ") != -1){
					temp = msg.substring(msg.indexOf(" "));
				} else {
					temp = msg;
				}
				ChatRobot.addMsg(temp);
			}
			
			int i = (int)(Math.random() * param.length);
			msg = HttpUtil.doGet(url, param[i] + msg, "UTF-8", true);
			if (msg != null) {
				JSONObject json = JSONObject.fromObject(msg);
				msg = StringUtil.objectToString(json.get("text"));
				String url = StringUtil.objectToString(json.get("url"), "");
				JSONArray list = (JSONArray) json.get("list");
				if(url.length() > 0){
					msg += "<br/><a href=\"" + url + "\" target=\"_blank\">点击打开链接</a>";
				}
				if(list != null){
					JSONObject obj = null;
					StringBuffer sb = new StringBuffer("");
					for(int j = 0, k = list.size(); j < k; j++){
						obj = (JSONObject) list.get(j);
						if(obj != null){
							sb.append("<div><a href=\"").append(StringUtil.objectToString(obj.get("detailurl"), "#"));
							sb.append("\" target=\"_balnk\">");
							sb.append(StringUtil.objectToString(obj.get("article"), "打开链接")).append("</a></div>");
						}
					}
					msg += sb.toString();
				}
				
				temp2 = StringUtil.filterHtml(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = "？";
		}
		if(tosoc == null){
			try {
				Thread.sleep(500 + timeout);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			sendAll(temp2);
		} else {
			send();
		}
	}

	public void send() {
		// msg = "";
		Map<String, String> fUser = ChatRobot.userMap.get(ChatRobot.ipUser.get(fromuser));
		if(fUser == null){
			 fUser = ChatRobot.userMap.get(fromuser);
		}
		if(fUser == null){
			String key = ChatServlet.ipUser.get(fromuser);
			ChatServlet.ipUser.remove(fromuser);
			if(key != null){
				ChatServlet.userMap.remove(fromuser);
				ChatServlet.socketMap.remove(fromuser);
			}
			return;
		}
		Map<String, Object> msgMap = new HashMap<String, Object>();
		msgMap.put("fromName", fUser.get("name"));
		msgMap.put("fromId", fUser.get("userId"));
		msgMap.put("msg", msg);
		msgMap.put("time", DateUtil.format(new Date()));
		msgMap.put("genre", 3);// 聊天
		msgMap.put("touser", touser);
		msgMap.put("flag", 2);// 私聊
		ChatServlet.getChat().sendMsgToClient(tosoc, ChatServlet.getChat().mapToJsonString(msgMap));
	}
	
	public void sendAll(String temp) {
		Map<String, String> fUser = ChatRobot.userMap.get(ChatRobot.ipUser.get(fromuser));
		if(fUser == null){
			fUser = ChatRobot.userMap.get(fromuser);
		}
		if(fUser != null){
			Map<String, String> toUser = ChatServlet.getUser(this.touser);
			if(toUser != null){
				msg = "<span class=\"tou atuser\" uid=\"" + this.touser + "\">@" + toUser.get("name") + "</span> " + msg;
			} else {
				Map<String, String> tUser = ChatRobot.userMap.get(ChatRobot.ipUser.get(touser));
				int r = (int)(Math.random() * 10);
				if(r > 5 && tUser != null){
					msg = "<span class=\"tou atuser\" uid=\"" + this.touser + "\">@" + tUser.get("name") + "</span> " + msg;
				}
			}
			Map<String, Object> msgMap = new HashMap<String, Object>();
			msgMap.put("fromName", fUser.get("name"));
			msgMap.put("fromId", fUser.get("userId"));
			msgMap.put("msg", msg);
			msgMap.put("time", DateUtil.format(new Date()));
			msgMap.put("genre", 3);// 聊天
			// 群聊
			String tUserId = null, iusid = "";
			for (Socket tosoc : ChatServlet.socketMap.values()) {
				if (tosoc != null) {
					iusid = ChatServlet.getUserId(tosoc);
					if (iusid != null) {
						if (!iusid.equals(fromuser)) {
							tUserId = iusid;
							msgMap.put("touser", tUserId);
							msgMap.put("flag", 1);// 群聊
							ChatServlet.getChat().sendMsgToClient(tosoc, ChatServlet.getChat().mapToJsonString(msgMap));
						}
					}
				}
			}
		}
		
		int r = (int)(Math.random() * 10);
		if(r != 4 && temp.length() > 1){
			if(temp.length() > 15){
				temp = temp.substring(0, 15);
			}
			if(!histroy[0].equals(temp) && !histroy[1].equals(temp)){
				JSONObject msgObj = new JSONObject();
				msgObj.put("content", temp);
				ChatServlet.cr.checkAndRe(null, fromuser, null, msgObj, 5000);
				
				histroy[0] = "";
				histroy[1] = "";
			} else {
				if(histroy[0].length() == 0){
					histroy[0] = temp;
				} else if(histroy[1].length() == 0){
					histroy[1] = temp;
				} else {
					histroy[0] = "";
				}
			}
		}
	}
	
	public String getRobot(String tos){
		Object[] ips = ChatRobot.ipUser.keySet().toArray();
		String fromuser = StringUtil.objectToString(ips[(int) (Math.random() * ips.length)]);
		int i = 0;
		while(fromuser.equals(tos) && i < 10){
			fromuser = StringUtil.objectToString(ips[(int) (Math.random() * ips.length)]);
		}
		return fromuser;
	}
}
